package org.nidy.erp.aop;

import org.nidy.erp.mapper.IOperateLogMapper;
import org.nidy.erp.utils.CurrentThreadArgs;
import org.nidy.erp.utils.OperateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private IOperateLogMapper operateLogMapper;
    @Around("@annotation(org.nidy.erp.anno.Log)")
    public Object operationLog(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long end=System.currentTimeMillis();
        long costTime=end-start;

        //构建操作日志对象
        OperateLog oLog=new OperateLog();
        oLog.setOperateEmpId(getCurrentUserId());
        oLog.setOperateTime(LocalDateTime.now());
        oLog.setClassName(joinPoint.getTarget().getClass().getName());
        oLog.setMethodName(joinPoint.getSignature().getName());
        oLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        oLog.setReturnValue(result !=null ? result.toString(): "void");
        oLog.setCostTime(costTime);
        //打印日志
        log.info("操作日志：{}",oLog);
        //保存日志
        operateLogMapper.insert(oLog);
        return result;

    }
    private Integer getCurrentUserId() {
        return CurrentThreadArgs.getCurrentId();
    }
}
